﻿using ItProto1;
using RFS.BizLogic.Sys.impl;
using RFS.BizLogic.utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using RFS.BizLogic.utils.impl;
using RFS.Domain.PaiShi.Zuhuo;
using DevExpress.XtraGrid;
using RFS.Domain.Sys;
using ycx;

namespace ProtoWinform
{
    public partial class FrmMainv2 : Form
    {
        private ILog _log;
        private IZuhuoManager _m;


        public FrmMainv2()
        {
            InitializeComponent();


            // Task.Run(() => ini());
            Ini();

            var f = new FrmLogin();
            f.StartPosition = FormStartPosition.CenterScreen;
            if (f.ShowDialog(this) != DialogResult.OK)
            {
                Application.Exit();
                Close();
            
            }

            _config.ConfigSys.CurrentUser = f.User;


        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);
            try
            {
                // WriteConfig();
            }
            catch (Exception exception)
            {
                _log.Err(exception);
            }
        }


        void Ini()
        {
            try
            {
                _log = AntiObject.Ins.Get<ILog>();
                _config = AntiObject.Ins.Get<IConfigT>();
                _log.NewLevedLogAdded += LogOnNewLevedLogAdded;

                _m = AntiObject.Ins.Get<IZuhuoManager>();

                _m.ZaHuaDataChanged += MOnZaHuaDataChanged;
                _m.ZuhuaDataChanged += MOnZuhuaDataChanged;

                EditModelZa = false;

                gconfig.Visible = false;
                
                gvZahua.FormatFontCondionaly((e) =>
                {
                    if (gvZahua.GetRow(e.RowHandle) is ZaHuaItem z) return z.ZhiLingItemId != 0;
                    else return false;
                }, Color.Green);

                dateEdit1.DateTime = DateTime.Now;
                Task.Run(() =>
                {
                    Thread.Sleep(1000);
                    bokclick(null, null);

                    ReadConfig();

                    // this.UseUiThread(() => ShowOnlyLeftover.Checked = true);
                });
            }
            catch (Exception e)
            {
                MessageBox.Show("错误：无法连接到数据库。请检查内网数据库连接。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                _log.Err(e);
                Console.WriteLine(e);
            }
        }

 

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            1.TryRun(() => saveLayout());
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            1.TryRun(() => LoadLayout());
        }

        private void LoadLayout()
        {
            var zu = _config.ConfigSys.ZuhuaGridLayout;
            var za = _config.ConfigSys.ZahuaGridLayout;

            if (!string.IsNullOrWhiteSpace(zu))
            {
                gcZuh.ForceInitialize();
                gcZuh.MainView.RestoreLayoutFromStream(zu.ToMemoStreamFromBase64());
            }

            if (!string.IsNullOrWhiteSpace(za))
            {
                gcZaH.ForceInitialize();
                gcZaH.MainView.RestoreLayoutFromStream(za.ToMemoStreamFromBase64());
            }

        }

        private void saveLayout()
        {

            using (MemoryStream stream = new MemoryStream())
            {
                gcZaH.MainView.SaveLayoutToStream(stream);
                _config.ConfigSys.ZahuaGridLayout = stream.ToStringBase64FromStream() ;
            }

            using (MemoryStream stream = new MemoryStream())
            {
                gcZuh.MainView.SaveLayoutToStream(stream);
                _config.ConfigSys.ZuhuaGridLayout = stream.ToStringBase64FromStream() ;
            }
            _config.SaveIt();
        }
        
        

        private int idx = 0;

        private void LogOnNewLevedLogAdded(object sender, (string log, LogLevel l) e)
        {
            var lv = e.l == LogLevel.Error ? "错误" : "消息";
            this.UseUiThread(() => { txtLogs.Text = $"{++idx} [{lv}] {e.log}\r\n{txtLogs.Text}"; });
        }

        private void MOnZuhuaDataChanged(object sender, IEnumerable<ZuhuaRecord> e)
        {
            this.UseUiThread(() => gcZuh.DataSource = e);
        }

        private void MOnZaHuaDataChanged(object sender, IEnumerable<ZaHuaItem> e)
        {
            this.UseUiThread(() => gcZaH.DataSource = e);
        }


        private void bokclick(object sender, EventArgs e)
        {
            _m.WorkingDay = this.dateEdit1.DateTime;
        }

        private void bCreateZuhuo_Click(object sender, EventArgs e)
        {
            // create
            _m.CreateAllZuhuo(gvZahua.GetSelectedObjects<ZaHuaItem>(), cbSaved.Checked, cb1keyGrouping.Checked);
        }

        private void ShowOnlyLeftover_CheckedChanged(object sender, EventArgs e)
        {
            if (ShowOnlyLeftover.Checked)
            {
                var v = this.gcZaH.MainView as GridView;
                v.Columns["指令时间"].FilterInfo = new ColumnFilterInfo("[指令时间] IS NULL");
            }
            else
            {
                this.gvZahua.Columns["指令时间"].FilterInfo = new ColumnFilterInfo("");
            }
        }

        private void gvZuhuo_FocusedRowChanged(object sender,
            DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            // Get the selected object
            if (gvZahua.GetFocusedRow() != null)
            {
                CurrentZuhuaRecord = (ZuhuaRecord)gvZuhuo.GetFocusedRow();
            }
        }


        public async Task ScanForPrinterAsync()
        {
            await Task.Run(() =>
            {
                List<string> printerNames = new List<string>();
                foreach (string printer in PrinterSettings.InstalledPrinters)
                {
                    printerNames.Add(printer);
                }

                return printerNames;
            });
        }


        private ZuhuaRecord _currentZuhuaRecord;
        private IConfigT _config;

        public ZuhuaRecord CurrentZuhuaRecord
        {
            get => _currentZuhuaRecord;
            set
            {
                _currentZuhuaRecord = value;
                Read();
            }
        }


        void Read()
        {
            if (_currentZuhuaRecord == null)
            {
                tZuNum.Text = $"";
                tId.Text = $"";

                拍市品种码.Text = $"";
                长度.Text = $"";
                复核人.Text = $"";

                录单人.Text = $"";
                供货商码.Text = $"";
                地块.Text = $"";
                gcCurrentZuItems.DataSource = new List<ZuhuaZiLingItem>();
                return;
            }

            tZuNum.Text = $"{_currentZuhuaRecord.发货单码}";
            tId.Text = $"{_currentZuhuaRecord.Id}";

            拍市品种码.Text = $"{_currentZuhuaRecord.拍市品种码}";
            长度.Text = $"{_currentZuhuaRecord.长度}";
            复核人.Text = $"{_currentZuhuaRecord.复核人}";

            录单人.Text = $"{_currentZuhuaRecord.录单人}";
            供货商码.Text = $"{_currentZuhuaRecord.供货商码}";
            地块.Text = $"{_currentZuhuaRecord.地块}";

            gcCurrentZuItems.DataSource = _currentZuhuaRecord.FaHuoZiLingItems;

            gcCurrentZuItems.RefreshDataSource();
            gcCurrentZuItems.ResumeLayout();
        }

        void WriteZuh()
        {
            if (_currentZuhuaRecord == null) return;

            _currentZuhuaRecord.发货单码 = tZuNum.Text;
            _currentZuhuaRecord.拍市品种码 = 拍市品种码.Text;
            _currentZuhuaRecord.长度 = 长度.Text;
            _currentZuhuaRecord.复核人 = 复核人.Text;
            _currentZuhuaRecord.录单人 = 录单人.Text;
            _currentZuhuaRecord.供货商码 = 供货商码.Text;
            _currentZuhuaRecord.地块 = 地块.Text;
        }


        private void bsave_Click(object sender, EventArgs e)
        {
            WriteZuh();
            //try to validate add to db
            _m.Add(_currentZuhuaRecord);
        }

        private void bsaveall_Click(object sender, EventArgs e)
        {
            _m.SaveAllAsync(gvZuhuo.GetSelectedObjects<ZuhuaRecord>());
        }


        private ZuhuoPrintForm doc;
        private bool _editModelZa = false;

        private void bDama_Click(object sender, EventArgs e)
        {
            //
            var d = new ZuhuoPrintForm(gvZuhuo.GetSelectedObjects<ZuhuaRecord>(), _config.ConfigSys.QunatityKipaPerZa);
            // this.printPreviewControl1.Document = d.PrintDocument;
            this.printPreviewDialog1.Document = d.PrintDocument;
            printPreviewDialog1.ShowDialog();
            doc = d;
        }

        private void bprintdict_Click(object sender, EventArgs e)
        {
            try
            {
                var d = new ZuhuoPrintForm(gvZuhuo.GetSelectedObjects<ZuhuaRecord>(),
                    _config.ConfigSys.QunatityKipaPerZa);
                d.PrintDocument.Print();
            }
            catch (Exception exception)
            {
                _log.Err(exception);
            }
        }

        private void bsecond_Click(object sender, EventArgs e)
        {
            _m.CreateFuZuhuo(gvZahua.GetSelectedObjects<ZaHuaItem>(), this.cbSaved.Checked);
        }


        private void cb1keyGrouping_CheckedChanged(object sender, EventArgs e)
        {
            //WriteConfig();
        }

        void WriteConfig()
        {
            1.TryRun(() =>
            {





                var c = _config.ConfigSys;
                c.Try1KeyGrouping = this.cb1keyGrouping.Checked;
                c.SaveAlsoZuhua = this.cbSaved.Checked;

                c.ZuhuoQuantityRangeMin = (int)this.minZhi.Value;
                c.ZuhuoQuantityRangeMax = (int)this.maxZhi.Value;

                c.QunatityKipaPerZa = (int)this.zhiPerZakipa.Value;

                c.ZuhuoEditor = this.tLuru.Text;
                c.ZuhuoDoubleChecker = this.tFuke.Text;
                c.KapiCodingBaseDate = this.bdKipa.DateTime;





            });

            //_config.Save(c);
            // c.QunatityKipaPerZa = (int)this.zhiPerZakipa.Value;
            // c.QunatityKipaPerZa = (int)this.zhiPerZakipa.Value;
        }


        void ReadConfig()
        {
            this.UseUiThread(() =>
            {
                var c = _config.ConfigSys;
                this.cb1keyGrouping.Checked = c.Try1KeyGrouping;
                this.cbSaved.Checked = c.SaveAlsoZuhua;

                this.minZhi.Value = c.ZuhuoQuantityRangeMin;
                this.maxZhi.Value = c.ZuhuoQuantityRangeMax;

                this.zhiPerZakipa.Value = c.QunatityKipaPerZa;
                this.tLuru.Text  = c.ZuhuoEditor;
                this.tFuke.Text  = c.ZuhuoDoubleChecker;
                this.bdKipa.DateTime= c.KapiCodingBaseDate  ;


            });
        }

        private void cbIncludeAllHistoryLeftOver_CheckedChanged(object sender, EventArgs e)
        {
            _m.LoadZaHuaSetAsync(date: default, cbIncludeAllHistoryLeftOver.Checked);
        }

        private void bSyncZahuaFromProd_Click(object sender, EventArgs e)
        {
            _m.SyncZahuaProductionData();
        }


        private void FrmMain3_KeyDown(object sender, KeyEventArgs e)
        {
            // if (e.Modifiers == Keys.Control && e.KeyCode == Keys.D)
            // {
            //     // Display a password prompt
            //     PasswordPromptForm passwordPrompt = new PasswordPromptForm();
            //     DialogResult result = passwordPrompt.ShowDialog(this);
            //     if (result == DialogResult.OK)
            //     {
            //         // Process the entered password
            //         string password = passwordPrompt.Pwd;
            //         if (password == _config.ConfigSys.DelPwd) 
            //             _m.Del(gvZuhuo.GetSelectedObjects<ZuhuaRecord>());
            //
            //         // ...
            //     }
            // }
        }

        private void gcZuh_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers == Keys.Control && e.KeyCode == Keys.D)
            {
                var data = gvZuhuo.GetSelectedObjects<ZuhuaRecord>();
                // Display a password prompt
                var f = new PasswordPromptForm();
                f.Msg = $"确定删除，已选择[{data.Count()}]项组货吗？";
                DialogResult result = f.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    // Process the entered password
                    string password = f.Pwd;
                    if (password == _config.ConfigSys.DelPwd)
                        _m.Del(data);
                    else
                    {
                        _log.Err(new Exception("密码错误，操作取消！"));
                    }

                    // ...
                }
            }

            if (e.Modifiers == Keys.Control && e.KeyCode == Keys.E)
            {
                var data = gvZuhuo.GetSelectedObjects<ZuhuaRecord>();
                // Display a password prompt
                var f = new FormChangedPwd();
                f.OldPwd = _config.ConfigSys.DelPwd;
                // f.Msg = $"确定删除，已选择[{data.Count()}]项组货吗？";
                DialogResult result = f.ShowDialog(this);
                if (result == DialogResult.OK)
                {

                    // Process the entered password
                    string password = f.Pwd;
                    _config.ConfigSys.DelPwd = password;
                    _config.SaveIt();
                    _log.Info("密码已修改！");


                }
            }

            
            
            if (e.Modifiers == Keys.Control && e.KeyCode == Keys.U)
            {
                if (_config.ConfigSys.CurrentUser!=null && _config.ConfigSys.CurrentUser.Name!= "admin") return;
                // var data = gvZuhuo.GetSelectedObjects<ZuhuaRecord>();
                // Display a password prompt
                var f = new frmUsers();
                // f.Msg = $"确定删除，已选择[{data.Count()}]项组货吗？";
                f.StartPosition = FormStartPosition.CenterScreen;
                DialogResult result = f.ShowDialog(this);
                if (result == DialogResult.OK)
                {



                }
            }


            
            if (e.Modifiers == Keys.Control && e.KeyCode == Keys.C)
            {
                if (_config.ConfigSys.CurrentUser!=null && _config.ConfigSys.CurrentUser.Name!= "admin") return;


                gconfig.Visible =! gconfig.Visible;

            }





        }

        private void zhiPerZakipa_ValueChanged(object sender, EventArgs e)
        {
        }

        private void bzuExcel_Click(object sender, EventArgs e)
        {
            gvZuhuo.ExcelEx("组花");
        }

        private void bzaExcel_Click(object sender, EventArgs e)
        {
            gvZahua.ExcelEx("扎花");
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {

            WriteConfig();
            _config.SaveIt();
        }

        private void bNewZuhua_Click(object sender, EventArgs e)
        {
            CurrentZuhuaRecord = _m.CopyToNew(_currentZuhuaRecord);
        }

        private void AddZahua_Click(object sender, EventArgs e)
        {
            _currentZuhuaRecord.addZahuas(gvZahua.GetSelectedObjects<ZaHuaItem>());
            this.gcCurrentZuItems.RefreshDataSource();
            _m.SaveAllAsync(new List<ZuhuaRecord>() { CurrentZuhuaRecord });
        }

        private void bcancelsavingaItem_Click(object sender, EventArgs e)
        {
        }

        private void bNewCreateZha_Click(object sender, EventArgs e)
        {
            var zs = _m.CopyOrCreateNewZaha(gvZahua.GetSelectedObject<ZaHuaItem>());
            // _currentZuhuaRecord.addZahuas(zs);
            // this.gcCurrentZuItems.RefreshDataSource();
        }

        private void bdel_Click(object sender, EventArgs e)
        {
            // 定义消息框的结果变量
            var d = gvZahua.GetSelectedObjects<ZaHuaItem>();

            // 显示消息框并获取用户选择
            var result = MessageBox.Show($"你确定要删除选定[{d.Count()}]扎花吗？", "确认",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Question);

            // 根据用户的选择执行不同操作
            if (result != DialogResult.Yes) return;

            _m.DelZas(d);
        }

        private void checkEdit1_Properties_EditValueChanged(object sender, EventArgs e)
        {
        }

        public bool EditModelZa
        {
            get => _editModelZa;
            set
            {
                _editModelZa = value;

                cbEdit.Checked = value;
                zaCDK.OptionsColumn.AllowEdit = value;
                zaCPz.OptionsColumn.AllowEdit = value;
                zaCGG.OptionsColumn.AllowEdit = value;
                zzCCD.OptionsColumn.AllowEdit = value;
                gvZahua.OptionsBehavior.Editable = value;
                gvZahua.OptionsBehavior.ReadOnly = !value;

                geditor.Visible = value;
                // zaCDK.OptionsColumn.AllowEdit = value;
                // zaCDK.OptionsColumn.AllowEdit = value;
            }
        }

        private void cbEdit_Click(object sender, EventArgs e)
        {
            Task.Run(() =>
            {
                Thread.Sleep(5);
                this.UseUiThread(() => EditModelZa = !EditModelZa);
            });
        }

        private void bSaveZa_Click(object sender, EventArgs e)
        {
            gvZahua.PostEditor();
            _m.SaveZahua(gvZahua.GetSelectedObject<ZaHuaItem>());
            EditModelZa = !EditModelZa;
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            // remove za
            _currentZuhuaRecord.RemoveZahuas(gvZahua.GetSelectedObjects<ZaHuaItem>());
            this.gcCurrentZuItems.RefreshDataSource();
            _m.SaveAllAsync(new List<ZuhuaRecord>() { CurrentZuhuaRecord });
        }

        private void gcZaH_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Modifiers == Keys.Control && e.KeyCode == Keys.D)
            {
                var data = gvZahua.GetSelectedObjects<ZaHuaItem>();
                // Display a password prompt
                var f = new PasswordPromptForm();
                f.Msg = $"确定删除，已选择[{data.Count()}]项扎花吗？";
                DialogResult result = f.ShowDialog(this);
                if (result == DialogResult.OK)
                {
                    // Process the entered password
                    string password = f.Pwd;
                    if (password == _config.ConfigSys.DelPwd)
                        _m.DelZas(data);
                    else
                    {
                        _log.Err(new Exception("密码错误，操作取消！"));
                    }
                }
            }
        }

        private void gvZuhuo_Click(object sender, EventArgs e)
        {
            CurrentZuhuaRecord = gvZuhuo.GetSelectedObject<ZuhuaRecord>();
        }

        private void bclean_Click(object sender, EventArgs e)
        {
            this.txtLogs.Text = "";
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            _m.SaveZahuas(gvZahua.GetSelectedObjects<ZaHuaItem>());
        }

        private void bUpdateTo_Click(object sender, EventArgs e)
        {
            var lr = (cbLuru.Checked, tLuru.Text);
            var fh = (cbFuke.Checked, tFuke.Text);

            _m.UpdateSelected(gvZuhuo.GetSelectedObjects<ZuhuaRecord>(), lr, fh);
            gcZuh.RefreshDataSource();

        }
    }
}